package cc.minos.servers.openfire.managers
{
	import flash.xml.XMLNode;
	import org.igniterealtime.xiff.collections.ArrayCollection;
	import org.igniterealtime.xiff.core.XMPPConnection;
	import org.igniterealtime.xiff.data.im.RosterGroup;
	import org.igniterealtime.xiff.data.IQ;
	import org.igniterealtime.xiff.data.sharedgroups.SharedGroupsExtension;
	import org.igniterealtime.xiff.data.XMPPStanza;
	import org.igniterealtime.xiff.events.RosterEvent;
	import org.igniterealtime.xiff.im.Roster;
	
	/**
	 * ...
	 * @author Minos
	 */
	public class RosterManager extends BasicManager
	{
		private var _sharedGroups:ArrayCollection;
		private var _roster:Roster;
		
		public function RosterManager( con:XMPPConnection )
		{
			super( con );
			_sharedGroups = new ArrayCollection();
			_roster = new Roster( con );
			_roster.addEventListener( RosterEvent.ROSTER_LOADED , function( e:RosterEvent ):void
				{
					retrieveSharedGroups();
				} );
		}
		
		public function fetchRoster():void
		{
			roster.fetchRoster();
		}
		
		private function retrieveSharedGroups():void
		{
			var iq:IQ = new IQ( null , IQ.TYPE_GET , XMPPStanza.generateID( "get_shared_groups_" ) , _receivedSharedGroups , null );
			iq.addExtension( new SharedGroupsExtension() );
			con.send( iq );
		}
		
		private function _receivedSharedGroups( resultIQ:IQ ):void
		{
			var iqNode:XMLNode;
			if ( !iqNode )
				return;
			
			var sharedgroupNode:XMLNode = iqNode.firstChild;
			if ( !sharedgroupNode )
				return;
			
			// Store the shared groups we received from the server
			for each ( var groupNode:XMLNode in sharedgroupNode.childNodes )
			{
				if ( groupNode.firstChild != null )
				{
					if ( !sharedGroups.contains( groupNode.firstChild.nodeValue ) )
					{
						sharedGroups.addItem( groupNode.firstChild.nodeValue );
					}
				}
			}
			
			updateLocalGroups();
		}
		
		/**
		 * Updates the collection of our locally cached groups, setting their
		 * 'shared' flag to indicate if they are shared groups or not.
		 */
		private function updateLocalGroups():void
		{
			for each ( var sharedGroupName:String in sharedGroups )
			{
				var rosterGroup:RosterGroup = roster.getGroup( sharedGroupName ) as RosterGroup;
				if ( rosterGroup )
					rosterGroup.shared = true;
			}
		}
		
		public function get roster():Roster
		{
			return _roster;
		}
		
		public function set roster( value:Roster ):void
		{
			_roster = value;
		}
		
		public function get sharedGroups():ArrayCollection 
		{
			return _sharedGroups;
		}
		
		public function set sharedGroups(value:ArrayCollection):void 
		{
			_sharedGroups = value;
		}
	
	}

}